package jmine.tec.report.impl.table.xls;

import java.util.Date;

import jmine.tec.report.api.table.ReportCell;
import jmine.tec.report.impl.table.ReportTableBuilder;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * @author finx
 * @created Apr 20, 2010
 */
public class TimestampCellXLSRenderer implements ReportCellXLSRenderer {

    private static final String TIMESTAMP_FORMAT = "m/d/yy h:mm";

    private static final String STYLE = "timestampContentStyle";

    /**
     * {@inheritDoc}
     */
    public void render(HSSFWorkbook workbook, HSSFCell hssfCell, ReportCell cell) {
        hssfCell.setCellValue((Date) cell.getValue());
        hssfCell.setCellStyle(this.getStyle(workbook, hssfCell));
    }

    /**
     * Obtém o estilo adequado para a célula de relatório contendo uma data.
     * 
     * @param workbook workbook
     * @param hssfCell hssfCell
     * @return HSSFCellStyle
     */
    private HSSFCellStyle getStyle(HSSFWorkbook workbook, HSSFCell hssfCell) {
        for (short i = 0; i < workbook.getNumCellStyles(); i++) {
            HSSFCellStyle style = workbook.getCellStyleAt(i);
            if (STYLE.equals(style.getUserStyleName())) {
                return style;
            }
        }
        HSSFCellStyle style = workbook.createCellStyle();
        style.cloneStyleFrom(hssfCell.getCellStyle());
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat(TIMESTAMP_FORMAT));
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setUserStyleName(STYLE);
        return style;
    }

    /**
     * {@inheritDoc}
     */
    public String getRendererType() {
        return ReportTableBuilder.TYPE_TIMESTAMP;
    }

}
